package com.example.research.service;

import com.example.research.dto.LoginRequest;
import com.example.research.dto.LoginResponse;
import com.example.research.entity.Role;
import com.example.research.entity.User;
import com.example.research.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证服务类
 */
@Service
public class AuthService {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户登录
     */
    public LoginResponse login(LoginRequest loginRequest) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();

        // 验证用户名和密码
        if (!userService.validatePassword(username, password)) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 获取用户信息
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("用户已被禁用");
        }

        // 生成JWT token
        String token = jwtUtils.generateToken(username, user.getId());

        // 获取用户角色
        List<String> roles = user.getRoles().stream()
                .map(Role::getRoleName)
                .collect(Collectors.toList());

        return new LoginResponse(token, username, user.getRealName(), roles, user.getId());
    }

    /**
     * 验证token
     */
    public boolean validateToken(String token) {
        return jwtUtils.isTokenValid(token);
    }

    /**
     * 从token获取用户名
     */
    public String getUsernameFromToken(String token) {
        return jwtUtils.getUsernameFromToken(token);
    }

    /**
     * 从token获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        return jwtUtils.getUserIdFromToken(token);
    }

    /**
     * 获取当前登录用户信息
     */
    public User getCurrentUser(String token) {
        String username = getUsernameFromToken(token);
        return userService.findByUsername(username);
    }
}
